// @algorithm @lc id=1000309 lang=cpp
// @title jC7MId

#include "algm/algm.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    // @test([-3])=-3
// @test([1,2,3])=6
public:
    int ans = INT_MIN;
    int maxPathSum(TreeNode *root) {
        int ans = INT_MIN;
        if (root == nullptr) {
            return INT_MIN;
        }
        if (root->left == nullptr && root->right == nullptr) {
            return root->val;
        }
        ans = root->val;
        ans = max(ans, maxPathSum(root->left));
        ans = max(ans, maxPathSum(root->right));
        ans = max(ans, root->val + helper(root->left) + helper(root->right));
        return ans;
    }

    int helper(TreeNode *root) {
        if (root == nullptr) {
            return 0;
        }
        return max(0, max(helper(root->left), helper(root->right)) + root->val);
    }
};